package com.learn.interceptor;

import com.alibaba.fastjson.JSON;
import com.learn.pojo.Result;
import com.learn.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        String url = req.getRequestURI();

        //看请求的资源是否为login
        if(url.contains("login")){
            log.info("登录操作，放行");
            return true;
        }

        //看Token是否为空
        String jwt = req.getHeader("token");
        if(jwt == null || jwt.trim().isEmpty() || jwt.split("\\.").length != 3 ){
            log.info("token为空，请登录");
            Result error = Result.error("NOT_LOGIN");
            String json = JSON.toJSONString(error);
            resp.getWriter().write(json);
            return false;
        }

        //如果JWT错误，则返回错误信息
        try {
            JwtUtil.parseJwt(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("token错误，请登录");
            Result error = Result.error("NOT_LOGIN");
            String json = JSON.toJSONString(error);
            resp.getWriter().write(json);
            return false;
        }

        log.info("token有效，放行");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
        System.out.println("postHandle...");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
        System.out.println("afterCompletion...");
    }
}
